package com.zmwx.subject.appliacion.context;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @Author: zmwx
 * @Date： 2024/4/7 22:52
 * @Describe： 登陆上下文对象
 */
public class LoginContextHolder {
    private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL_TEST
            = new ThreadLocal<>();
    private static final InheritableThreadLocal<Map<String, Object>> THREAD_LOCAL
            = new InheritableThreadLocal<>();

    public static void set(String key, Object value) {
        Map<String, Object> map = getThreadLocalMap();
        map.put(key, value);
        THREAD_LOCAL.set(map);
    }

    public static Map<String, Object> getThreadLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (Objects.isNull(map)) {
            map = new ConcurrentHashMap<>();//线程安全的map
        }
        return map;
    }

    public static String getLoginId() {
        Map<String, Object> map = getThreadLocalMap();
        return (String)map.get("loginId");
    }

    public static Object get(String key) {
        Map<String, Object> map = THREAD_LOCAL.get();
        return map.get(key);
    }

    public static void remove() {
        THREAD_LOCAL.remove();
    }
}
